import time
import json

from datetime import date
from datetime import datetime
import decimal
class JsonExtendEncoder(json.JSONEncoder):
    """
        This class provide an extension to json serialization for datetime/date.
    """
    def default(self, o):
        """
            provide a interface for datetime/date
        """
        if isinstance(o, datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(o, date):
            return o.strftime('%Y-%m-%d')
        if isinstance(o, decimal.Decimal): 
            #return (str(o) for o in [o])
            return float(str(o))
        else:
            return json.JSONEncoder.default(self, o) 
class TUtils:
    def __init__(self) -> None:
        pass
    
    @staticmethod
    def getSvrTime():
        return str( time.time() )
    
    """
    获取WEB提交的请求参数数据
    """
    @staticmethod
    def getRequestData( request ):
        res ={
            "ps":{},
            "bodyContent":"",
            "files":[]
        }
        try:
            for k in request.FILES.keys():
                try:
                    res["files"][k] = request.FILES.get(k)[0] 
                except Exception as eer:
                    pass
            if request.method=="POST":
                bodyContent = request.body.decode('utf-8')
                res["bodyContent"] = bodyContent
                try:
                    bodyObj = json.loads(bodyContent)
                    for k in bodyObj.keys():
                        res["ps"][k] = bodyObj[k] 
                except Exception as eer:
                    print('comm.getPostData convert body to json error.') 
                    print(eer)
                for k in request.POST.keys():
                    try:
                        res["ps"][k] = request.POST.get(k)[0]
                    except Exception as eer:
                        pass
            elif request.method == "GET":
                for k in request.POST.keys():
                    try:
                        res["ps"][k] = request.GET.get(k)[0]
                    except Exception as eer:
                        pass

        except Exception as er:
            print('comm.getPostData error.') 
            print(er)
        return res
    
class TRequestResult:
    def __init__(self) -> None:
        self.result = None
        self.errCode = 0
        self.errMsg = ""
    def toDict(self):
        res = {
            "result": None,
            "errCode":self.errCode ,
            "errMsg":self.errMsg
        }
        if self.result!=None:
            res["result"] = self.result
        return res
    def toJson(self):
        resDict = self.toDict()
        res = json.dumps( resDict , ensure_ascii=False, cls=JsonExtendEncoder)
        return res